<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>批量修改图片尺寸</title>
    <style>
        .image-preview {
            margin-top: 20px;
            width: 100%;
        }

        .image-container {
            display: inline-block;
            margin: 10px;
        }

        .image-container img {
            width: 50px;
            height: auto;
            display: block;
        }
    </style>

    <script src="./js/jquery-1.11.1.min.js"></script>
    <script src="./js/jszip.min.js"></script>
    <script src="./js/FileSaver.js"></script>
</head>

<body>
    <h1>批量修改图片尺寸</h1>
    <input type="file" id="fileInput" multiple accept="image/*">
    <br><br>
    
    <!-- <label for="modeLabel">修改模式</label>
    <input type="radio" id="modeWidth" name="type" value="width">
    <label for="modeWidth">宽</label>
    <input type="radio" id="modeHeight" name="type" value="height">
    <label for="modeHeight">高</label>
    <br>
    <br> -->
    <label for="resizeMode">调整模式：</label>
    <select id="resizeMode">
        <option value="width">按宽度调整</option>
        <option value="height">按高度调整</option>
    </select>
    <br><br>
    <label for="sizeThreshold">尺寸大于多少修改尺寸：</label>
    <input type="number" id="sizeThreshold" placeholder="尺寸阈值">
    <br><br>
    <label for="newSize">修改后的尺寸：</label>
    <input type="number" id="newSize" placeholder="新尺寸">
    <br><br>
    <button id="resizeButton">修改图片尺寸</button>

    <button id="saveButton">保存修改后的图片</button>
    <span>
        总数：<span id="total"></span>，成功数量：<span id="successCount"></span>，失败数量：<span id="failedCount"></span>
    </span>

    <div class="image-preview" id="imagePreview"></div>

    <script>
        var saveImages = [];
        document.getElementById('resizeButton').addEventListener('click', function () {
            const files = document.getElementById('fileInput').files;
            const resizeMode = document.getElementById('resizeMode').value;
            const sizeThreshold = parseInt(document.getElementById('sizeThreshold').value, 10);
            const newSize = parseInt(document.getElementById('newSize').value, 10);

            if (isNaN(sizeThreshold) || isNaN(newSize)) {
                alert('请填写有效的尺寸阈值和新尺寸。');
                return;
            }

            const previewContainer = document.getElementById('imagePreview');
            previewContainer.innerHTML = ''; // 清空预览区域

            saveImages = [];

            Array.from(files).forEach(file => {
                console.log(file)
                const reader = new FileReader();
                reader.onload = function (e) {
                    const img = new Image();
                    img.onload = function () {

                        let canvas = document.createElement('canvas');
                        let ctx = canvas.getContext('2d');

                        if (resizeMode === 'width' && img.width > sizeThreshold) {
                            const scaleFactor = newSize / img.width;
                            canvas.width = newSize;
                            canvas.height = img.height * scaleFactor;
                        } else if (resizeMode === 'height' && img.height > sizeThreshold) {
                            const scaleFactor = newSize / img.height;
                            canvas.width = img.width * scaleFactor;
                            canvas.height = newSize;
                        } else {
                            // 如果图片不需要调整，则直接显示
                            const container = document.createElement('div');
                            container.classList.add('image-container');
                            container.appendChild(img);
                            previewContainer.appendChild(container);

                            saveImages.push({
                                name: file.name,
                                dataURL: img.src
                            })
                            return;
                        }

                        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

                        const resizedImg = new Image();
                        resizedImg.src = canvas.toDataURL('image/jpeg');

                        const container = document.createElement('div');
                        container.classList.add('image-container');
                        container.appendChild(resizedImg);
                        previewContainer.appendChild(container);

                        saveImages.push({
                            name: file.name,
                            dataURL: resizedImg.src
                        })
                    }
                    img.src = e.target.result;
                }
                reader.readAsDataURL(file);
            });
        });

        document.getElementById('saveButton').addEventListener('click', function () {
            if (saveImages.length === 0) {
                alert('暂无图片');
                return;
            }
            downloadAndCompressFiles(saveImages, null, (successCb, failedCb) => {
                // document.getElementById('downloadButton').textContent = '开始下载';
                // document.getElementById('downloadButton').disabled = false;
                // console.log('成功数量', successCb || 0)
                // console.log('失败数量', failedCb || 0)
            }, (progressRes) => {
                document.getElementById('total').innerText = progressRes.total;
                document.getElementById('successCount').innerText = progressRes.successCount;
                document.getElementById('failedCount').innerText = progressRes.failedCount;
            })
        });

        function base64ToBlob(dataurl) {
            let arr = dataurl.split(',')
            let mime = arr[0].match(/:(.*?);/)[1]
            let bstr = atob(arr[1])
            let n = bstr.length
            let u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new Blob([u8arr], { type: mime })
        }

        function downloadAndCompressFiles(fileList, outputName, callback, progressCb) {
            console.log('fileList', fileList);
            // 创建一个新的JSZip实例
            let zip = new JSZip();
            let fileNames = [];

            // 用于追踪已下载的文件数量和下载失败的文件数量
            let downloadedFiles = 0;
            let failedFiles = 0;

            // 遍历文件列表，下载并添加到压缩包中
            fileList.forEach(function (item, index) {
                // let originalFileName = getFileName(url, true);
                let blob = base64ToBlob(item.dataURL);
                let fileName = item.name;

                // 重名文件，添加序号
                if (fileNames.includes(fileName)) {
                    let count = 1;
                    let baseName = fileName.replace(/\.[^/.]+$/, ''); // Remove extension from filename
                    let extension = fileName.split('.').pop(); // Get the extension of the file

                    while (fileNames.includes(fileName)) {
                        fileName = baseName + '(' + count + ').' + extension;
                        count++;
                    }
                }
                // 将文件数据添加到压缩包中
                zip.file(fileName, blob);
                fileNames.push(fileName);

                // 更新已下载的文件数量
                downloadedFiles++;

                progressCb({
                    total: fileList.length,
                    failedCount: failedFiles,
                    successCount: downloadedFiles,
                })

                // 检查是否所有文件都已下载完成
                if (downloadedFiles === fileList.length) {
                    // 检查是否有文件下载失败
                    if (failedFiles === 0) {
                        // 生成压缩包
                        zip.generateAsync({ type: 'blob' }).then(function (content) {
                            // 确定保存的文件名
                            let saveFileName;
                            if (outputName) {
                                saveFileName = outputName.endsWith('.zip') ? outputName : outputName + '.zip';
                            } else {
                                saveFileName = 'download.zip';
                            }

                            // 使用file-saver库保存压缩包
                            saveAs(content, saveFileName);

                            // 调用回调函数，传递下载成功的文件数量
                            if (callback) {
                                callback(downloadedFiles);
                            }
                        });
                    } else {
                        // 调用回调函数，传递下载成功的文件数量和下载失败的文件数量
                        if (callback) {
                            callback(downloadedFiles, failedFiles);
                        }
                    }
                }
            });
        }
    </script>
</body>

</html>